//
//  ViewController.m
//  GCD常用函数
//
//  Created by 李煜 on 2024/3/20.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

//  [self groupOldStyle];
//  [self groupOldStyleWait];
  [self groupNewStyle];
}
- (void)groupOldStyle {
  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t group = dispatch_group_create();

  //***注意: enter和leave必须成对出现
  //enter后的任务会添加到group
  dispatch_group_enter(group);
  dispatch_async(queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--download1--%d--%@",i,[NSThread currentThread]);
    }
    //leave会退出group
    dispatch_group_leave(group);
  });

  dispatch_group_enter(group);
  dispatch_async(queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--download2--%d--%@",i,[NSThread currentThread]);
    }
    dispatch_group_leave(group);
  });

  //拦截监听group中任务都完成时调用如下代码
  //group_notify不是线程阻塞的,是异步执行的
  dispatch_group_notify(group, queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--group_notify--%d--%@",i,[NSThread currentThread]);
    }
  });

  NSLog(@"--end--检查group_notify是否异步");
}
- (void)groupOldStyleWait {
  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t group = dispatch_group_create();

  //***注意: enter和leave必须成对出现
  //enter后的任务会添加到group
  dispatch_group_enter(group);
  dispatch_async(queue, ^{
    for (int i = 0 ; i<100; i++) {
      NSLog(@"--download1--%d--%@",i,[NSThread currentThread]);
    }
    //leave会退出group
    dispatch_group_leave(group);
  });

  dispatch_group_enter(group);
  dispatch_async(queue, ^{
    for (int i = 0 ; i<100; i++) {
      NSLog(@"--download2--%d--%@",i,[NSThread currentThread]);
    }
    dispatch_group_leave(group);
  });
  //死等,dispatch_group_wait是线程阻塞,必须上面任务都完成才执行下面代码
  dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

  dispatch_group_enter(group);
  dispatch_async(queue, ^{
    for (int i = 0 ; i<100; i++) {
      NSLog(@"--wait--%d--%@",i,[NSThread currentThread]);
    }
    dispatch_group_leave(group);
  });

  NSLog(@"--end--检查group_notify是否异步");
}
- (void)groupNewStyle {
  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  dispatch_group_t group = dispatch_group_create();
  dispatch_group_async(group, queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--download1--%d--%@",i,[NSThread currentThread]);
    }

  });
  dispatch_group_async(group, queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--download2--%d--%@",i,[NSThread currentThread]);
    }
  });

  dispatch_group_notify(group, queue, ^{
    for (int i = 0 ; i<1000; i++) {
      NSLog(@"--download3--%d--%@",i,[NSThread currentThread]);
    }
  });
}



@end
